
from home.models import User
from django import forms

class HomeForm(forms.ModelForm):
    username = forms.CharField(max_length=20,required=True,error_messages={
        'max_lenght':'用户名太长了',
        'required':'必要参数'
    })
    age = forms.IntegerField()
    active = forms.BooleanField()

    def cleaned(self, *args,**kwargs):
        # 校验所有参数
        # 关于详情请查看官方文档

        return super().cleand_data(*args,**kwargs)

    def cleaned_username(self,*args,**kwargs):
        # 校验指定参数
        # 关于详情请查看官方文档
        return super().cleaned_username(*args,**kwargs)
    
    def save(self):
        user = User()
        for k,v in self.cleaned_data.items():
            if User.objects.filter(**self.cleaned_data):
                # raise forms.ValidationError('重复添加')
                # self.add_error('重复添加',200)
                return True
            setattr(user,k,v)
        user.save()

    class Meta:
        model = User
        fields = ('username','age','active',)